import httpApi from '@/network/api'
import storage from '@/utils/storage.js'
import util from '@/utils/index.js'
import base from '@/base/index.js'

export default {
	state: {
		token: storage.get('user_token', ""), //登录信息
		userInfo: storage.get('user_userInfo', {}), //用户信息
		authInfo: storage.get('user_authInfo', null), //认证信息
	},
	mutations: {
		SET_token(state, value = '') {
			state.token = value
			storage.set('user_token', value)
		},
		SET_userInfo(state, info = {}) {
			state.userInfo = info
			storage.set('user_userInfo', info)
		},
		SET_authInfo(state, info = {}) {
			state.authInfo = info
			storage.set('user_authInfo', info)
		},
	},
	actions: {
		// ===================登录相关接口======================
		// 去登录
		do_login({
			dispatch
		}) {
			uni.redirectTo({
				url: '/pages/login/login'
			})
		},

		// 账号密码登录
		password_login({
			dispatch
		}, params) {
			return httpApi.api.gate_user_login(params).then((res) => {
				return res
			})
		},

		//短信验证码登录
		mobileCode_login({
			dispatch
		}, params) {
			return httpApi.api.gate_user_mobilelogin(params).then((res) => {
				return res
			})
		},

		//获取用户真实信息
		get_authUserRealInfo({
			dispatch,
			commit
		}) {
			return httpApi.api.get_user_realInfo().then((res) => {
				commit('SET_authInfo', res)
				return res
			})
		},


		// 统一处理登录之后的事物
		handle_login_after_thing({
			dispatch,
			commit
		}, userinfo) {
			commit('SET_token', userinfo.token)
			commit('SET_userInfo', userinfo)
			dispatch('get_authUserRealInfo')
		},

		// 执行退出
		do_logout({
			dispatch
		}) {
			return httpApi.api.gate_user_logout().then(res => {
				dispatch('clear_loginInfo')
				return res
			})
		},

		// 清理登录信息
		clear_loginInfo({
			dispatch,
			commit,
		}) {
			commit('SET_token', '')
			commit('SET_userInfo', {})
			commit('SET_authInfo', {})
		},

		//获取用户信息
		get_userInfo({
			dispatch,
			commit
		}) {
			return httpApi.api.get_user_info().then(res => {
				commit('SET_userInfo', res.userinfo)
				return res
			})
		},

		//获取微信code
		get_wechatCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true, //仅请求授权认证
					success: (data) => {
						httpApi.api.get_wechat_code({
							// #ifdef APP
							client_type: 'APP',
							// #endif
							// #ifdef MP-WEIXIN
							client_type: 'Wechat',
							// #endif
							code: data.code
						}).then((res) => {
							resolve(res);
						}).catch((error) => {
							reject(error);
						});
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
		}
	},
	getters: {
		token: state => state.token,
		userInfo: state => {
			return {
				...state.userInfo,
				nickname: state.authInfo && state.authInfo.status == 1 ? state.authInfo.realname : state.userInfo.nickname,
				avatar: state.userInfo?.avatar ? base.imgUrl(state.userInfo.avatar) : '/static/home/default-user.png'
			}
		},
		authInfo: state => state.authInfo
	}
}